//
//  ColelctViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/20.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ColelctViewController.h"
#import "CollectCell.h"
#import "CollectHeadView.h"
//#import "ColectFooterView.h"
#import "GoodsDetailViewController.h"
#import "StoreViewController.h"
@interface ColelctViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation ColelctViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if(!ISNOTNEEDMESSAGEBTN){
        self.isNeedMessageItem = YES;
    }
    self.dataSource = [NSMutableArray array];
    self.vcName = @"我的收藏";
     [self tableViewAndHeaderView];
    [self loadData];
}

-(void)loadData{
    //2.32查看我的收藏接口
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              };
    __weak typeof(self)  weakSelf = self;
   [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:GETMYCOLLECTION paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
          DLog(@"我的收藏接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSArray *dataArr = resultDic[@"data"];
             if([dataArr isKindOfClass:[NSNull class]]){
                 [MBProgressHUD dismissHUD];
                 return ;
               }
                for(NSDictionary *dic in dataArr){
                    CollectGroup *group = [[CollectGroup alloc]init];
                    group.storeId = dic[@"storeId"];
                    group.storeName = dic[@"storeName"];
                    NSArray *products = dic[@"products"];
                    NSMutableArray *pArr = [NSMutableArray array];
                    for(NSDictionary *pDic in products){
                        if(![pDic[@"pName"] isKindOfClass:[NSNull class]]&&![pDic[@"pPrice"] isKindOfClass:[NSNull class]]){
                        CollectModel *model= [[CollectModel alloc]init];
                        model.productId = pDic[@"pId"];
                        model.pPrice = [NSString stringWithFormat:@"%@",pDic[@"pPrice"]];
                        model.pName = pDic[@"pName"];
                        model.pPic = pDic[@"pPic"];
                        model.pIntroduce = pDic[@"pIntroduce"];
                        [pArr addObject:model];
                      }
                      group.products = pArr;
                   }
                    [weakSelf.dataSource addObject:group];
                }
            if(!weakSelf.dataSource.count){
                [MBProgressHUD dismissHUD];
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
                return;
            }
                dispatch_async(dispatch_get_main_queue(), ^{
                    //刷新页面
                    [self.tableV reloadData];
                    self.tableV.hidden = NO;
                    [MBProgressHUD dismissHUD];
                });
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = DEF_COLOR242;
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.separatorStyle =UITableViewCellSeparatorStyleNone;
    _tableV.hidden = YES;
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     CollectGroup *group = self.dataSource[section];
    NSArray *products = group.products;
    return products.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"acwtell";
    CollectCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"CollectCell" owner:self options:nil]lastObject];
    }
    CollectGroup *group = self.dataSource[indexPath.section];
    CollectModel *model =group.products[indexPath.row];
    __weak typeof(self)  weakSelf = self;
    //取消收藏回调
    cell.cancelCollectBlock = ^(){
        [weakSelf cancelCollectionWithIndexPath:indexPath];
    };
    cell.model = model;
    return cell;
}

//2.33取消收藏接口
-(void)cancelCollectionWithIndexPath:(NSIndexPath *)indexPath{
    CollectGroup *group = self.dataSource[indexPath.section];
    NSMutableArray *products = group.products;
    CollectModel *model =products[indexPath.row];
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              @"productId":model.productId
                              };
    [Tools AFNetworkingRequestTypePostWithUrl:DELETECOLLECTION paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){
                [MBProgressHUD showTipMessageInWindow:@"取消成功"];
                //回到主线程刷新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (products.count) {
                        [products removeObjectAtIndex:indexPath.row];
                        DLog(@"1删除了 %d", products.count);
                        if ( products.count==0) {
                            [self.dataSource removeObjectAtIndex:indexPath.section];
                            if(self.dataSource.count==0){
                                self.tableV.hidden = YES;
                                return ;
                            }
                            if(indexPath.section==self.dataSource.count){
                                  [self.tableV reloadData];
                                  return;
                            }
                            [self.tableV deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                             [self.tableV reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                            return;
                        }
                        if(products.count==indexPath.row){
                            [self.tableV reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                        }else{
                            // 删除其他的cell
                            [self.tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            [self.tableV reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        }
                    }
                });
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 94;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 32;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 5;
//}

//自定义头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *headID = @"head";
    CollectHeadView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if(headView==nil){
        headView = [[[NSBundle mainBundle]loadNibNamed:@"CollectHeadView" owner:self options:nil]lastObject];
    }
    CollectGroup *group = self.dataSource[section];
    headView.group = group;
    __weak typeof(self) weakSelf = self;
    headView.tapBlock = ^{
        //跳转到店铺
        StoreViewController *goodsDetail  = [[StoreViewController alloc]init];
        goodsDetail.storeId =group.storeId ;
        goodsDetail.vcName = group.storeName;
        [weakSelf.navigationController pushViewController:goodsDetail animated:YES];
    };
    return headView;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    NSString *headID = @"footer";
//    ColectFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
//    if(footerView==nil){
//        footerView = [[[NSBundle mainBundle]loadNibNamed:@"ColectFooterView" owner:self options:nil]lastObject];
//    }
//    return footerView;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CollectGroup *group = self.dataSource[indexPath.section];
    CollectModel *model =group.products[indexPath.row];
    GoodsDetailViewController *goodsDetail  = [[GoodsDetailViewController alloc]init];
    goodsDetail.pid = model.productId;
    goodsDetail.goodPic = model.pPic;
    goodsDetail.isNeedMessageItem = YES;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
